import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/internal/operators';
import { Song, SongUrl, Lyric } from './data-types/common.type';
import { API_CONFIG, ServicesModule } from './services.module';


@Injectable({
  providedIn: ServicesModule
})
export class SongService {

  constructor(private http: HttpClient, @Inject(API_CONFIG) private url: string) { }
  getSongUrl(ids: string): Observable<SongUrl[]> {
    const params = new HttpParams().set('id', ids);
    return this.http.get(this.url + '/song/url', {params})
      .pipe(map((res: { data: SongUrl[] }) => res.data));
  }
  getSongList(songs) {
    const songList = Array.isArray(songs) ? songs.slice() : [songs];
    const ids = songList.map(song => song.id).join(',');
    return this.getSongUrl(ids).pipe(map(urls => this.generateList(songList, urls)));
  }
  getSongDetail(ids: string): Observable<Song> {
    const params = new HttpParams().set('ids', ids);
    return this.http.get(this.url + '/song/detail', {params})
      .pipe(map((res: { songs: Song }) => res.songs[0]));
  }
  getLyric(id: number): Observable<Lyric> {
    const params = new HttpParams().set('id', id.toString());
    return this.http.get(this.url + '/lyric', { params })
    .pipe(map((res: { [key: string]: { lyric: string; } }) => {
      try {
        return {
          lyric: res.lrc.lyric,
          tlyric: res.tlyric.lyric
        };
      } catch (err) {
        return {
          lyric: '',
          tlyric: ''
        };
      }
    }));
  }
  private generateList(songs: Song[], urls: SongUrl[]): Song[] {
    const songList = [];
    songs.forEach((song: Song) => {
      const url = urls.find(item => song.id === item.id).url;
      songList.push({
        ...song,
        url
      });
    });
    return songList;
  }
}
